<?php
namespace app\common\model;
use think\Model;
use think\facade\Db;
use think\model\concern\SoftDelete;

class Category extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;

    /**
     * 关联模型
     * @return Category|\think\model\relation\BelongsTo
     */
    public function model()
    {
        return $this->belongsTo(DictData::class,'model','id')->bind(['model_name'=>'name']);
    }
    /**
     * 新增后更新URL
     * @param Model $data
     * @return bool
     */
    public static function onAfterInsert($data)
    {
        if($data['model'] == 5){
            return true;
        }else{
            $url = '/lists/'.$data['id'].'.html';
            self::where(['id'=>$data['id']])->update(['url'=>$url]);
            return true;
        }
    }
    /**
     * 新增后更新URL
     * @param Model $data
     * @return bool
     */
    public static function onAfterUpdate($data)
    {
        if($data['model'] == 5){
            return true;
        }else{
            $url = '/lists/'.$data['id'].'.html';
            self::where(['id'=>$data['id']])->update(['url'=>$url]);
            return true;
        }
    }

    /**
     * 获取权限组列表
     * @param string $form
     * @return array
     */
    static function list_to_level($form='') {
        if(empty($form)){
            $list = list_to_level(self::where('status',1)->order('sort_order desc,id desc')->select());
        }else{
            $id = DictData::where(['dict_id'=>1,'value'=>$form])->value('id');
            $list = list_to_level(self::where(['status'=>1,'model'=>$id])->order('sort_order desc,id desc')->select());
        }
        return $list;
    }

    /**
     * 获取列表
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static function get_list($form)
    {
        if(empty($form)){
            return self::where('status',1)->order('sort_order desc,id desc')->select();
        }else{
            $id = DictData::where(['dict_id'=>1,'value'=>$form])->value('id');
            return self::where(['status'=>1,'model'=>$id])->order('sort_order desc,id desc')->select();
        }

    }

}